package main

import (
	"fmt"
	"sync"
	"time"
)

type CircleQueue struct {
	HeadIndex int
	TailIndex int
	MaxSize   int
	arr       [5]int
	Lock      sync.Mutex
}

func (this *CircleQueue) IsFull() bool {
	return (this.TailIndex+1)%this.MaxSize == this.HeadIndex
}

func (this *CircleQueue) IsEmpty() bool {
	return this.HeadIndex == this.TailIndex
}

func (this *CircleQueue) Pop() (val int, err error) {
	this.Lock.Lock()
	for {
		if this.IsEmpty() {
			//return 0, fmt.Errorf("队列为空")
			time.Sleep(time.Microsecond * 50)
			continue
		}
		val = this.arr[this.HeadIndex]
		this.HeadIndex = (this.HeadIndex + 1) % this.MaxSize
		this.Lock.Unlock()
		return
	}
}

func (this *CircleQueue) Push(val int) (err error) {
	if this.IsFull() {
		return fmt.Errorf("队列已满")
	}
	this.arr[this.TailIndex] = val
	this.TailIndex = (this.TailIndex + 1) % this.MaxSize
	return nil
}

func (this *CircleQueue) Size() int {
	return (this.TailIndex + this.MaxSize - this.HeadIndex) % this.MaxSize
}

func (this *CircleQueue) ListQueue() {
	size := this.Size()
	if size <= 0 {
		fmt.Println("队列为空")
		return
	}
	tempHead := this.HeadIndex
	for i := 0; i < size; i++ {
		fmt.Printf("arr[%d]=%v\t", tempHead, this.arr[tempHead])
		tempHead = (tempHead + 1) % this.MaxSize
	}
	fmt.Println()
}
